#!/usr/bin/python
#
# main.py
# Copyright (C) Ethan Osten 2007 <senoki@gmail.com>
# 
# main.py is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
# 
# main.py is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
# 
# You should have received a copy of the GNU Lesser General Public
# License along with main.py.  If not, write to:
# 	The Free Software Foundation, Inc.,
# 	51 Franklin Street, Fifth Floor
# 	Boston, MA  02110-1301, USA.

import ctypes, sys
import gtk, gobject
import pynotify
import dbus, dbus.service, dbus.glib
import dieu.settings, dieu.database, dieu.bookmark, dieu.inet, dieu.listen, dieu.util
import dieu.gui.add, dieu.gui.about, dieu.gui.prefs, dieu.gui.edit, dieu.gui.tray, dieu.gui.browser
from optparse import OptionParser
pynotify.init('Dieu')

if __name__ == '__main__':
    try:
        if dieu.inet.test_dbus('org.gnome.Dieu') == False:
            libc = ctypes.CDLL('libc.so.6')
            libc.prctl(15, 'dieu', 0, 0, 0)
            
            parsing = OptionParser()
            parsing.add_option("-n", "--title", dest="title", help="Start dialog with the title field set to NAME", metavar="NAME")
            parsing.add_option("-u", "--url", dest="posturl", help="Start dialog with the URL field set to POSTURL", metavar="POSTURL")
            parsing.add_option("-e", "--extended", dest="description", help="Start dialog with the description field set to DESC", metavar="DESC")
            parsing.add_option("-t",  "--tags", dest="tags", help="Start dialog with the tags field set to TAGS", metavar="TAGS")
            (options, args) = parsing.parse_args()
            
            dieu_trayicon = dieu.gui.tray.DieuTrayIcon()
            
            if dieu.settings.get_default_user() == None:
                dieu.gui.prefs.DieuNewAccount()
            
            session_bus = dbus.SessionBus()
            bus_name = dbus.service.BusName('org.gnome.Dieu', bus = session_bus)
            listen = dieu.listen.DieuListen(bus_name, dieu_trayicon)
            
            gobject.threads_init()
            gtk.gdk.threads_init()
            gobject.MainLoop().run()
            gtk.main()
        else:
            print ''
            print 'Dieu is already running.'
            print ''
    except KeyboardInterrupt:
        print ''
        print 'Received interrupt from user - shutting down.'
        print ''
        sys.exit()
